<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const { pageData } = useData();
import {
  ftpCfgGet,
  ftpCfgSet,
  getDataByPage,
  cfgBackupRecovery,
  cfgBackupDownload,
  cfgBackupDel,
  cfgBackupUpload,
  cfgBackup
} from "@/api/modules/system/backup";
import { downloadTemplate, exportData, importData } from "@/api/modules/resource/host-finger";
import moment from "moment/moment";
import UpdateForm from "@/views/system/account/components/UpdateForm/index.vue";

const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    isWarnCount: 1,
    warn_rule: false,
    plug_rule: false,
    isBlockCount: 1,
    login_warn: false,
    loginWarnBlock: false,
    loginWarnCount: 0,
    data: []
  },
  responseKey: {
    list: "data",
    total: "total"
  }
});

// 获取列表数据
const loading = ref(false);

function findCombinations(arr, target) {
  const results = [];

  // 辅助函数，用于递归查找组合
  function backtrack(start, path, currentSum) {
    if (currentSum === target) {
      // 找到符合条件的组合，添加到结果中
      results.push([...path]);
      return;
    }
    if (currentSum > target) {
      return; // 超过目标和，返回
    }

    for (let i = start; i < arr.length; i++) {
      path.push(arr[i]); // 添加当前元素
      backtrack(i, path, currentSum + arr[i]); // 递归查找
      path.pop(); // 回溯，移除当前元素
    }
  }

  backtrack(0, [], 0); // 初始化递归
  return results?.length ? [results[results.length - 1]][0] : []; // 返回所有符合条件的组合
}

const originData = ref({});

async function ftpCfgGetCb() {
  const res = await ftpCfgGet();
  formData.interval = res.interval;
  if (Number(formData.interval)) {
    formData.isInterval = true;
  }
  formData.data = findCombinations([1, 2, 4], res.data);
  originData.value = res;
  loadDataCb();
}

ftpCfgGetCb();

async function ftpCfgSetCb() {
  console.log("formData.data", formData.data);
  let count = 0;
  for (let i = 0; i < formData.data.length; i++) {
    count += formData.data[i];
  }
  console.log(count);
  const res = await ftpCfgSet({
    ...originData.value,
    interval: formData.isInterval ? formData.interval : 0,
    data: count
  });
  ftpCfgGetCb();
  ElMessage.success("保存成功");
}

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize
    }
  });
}

loadDataCb();

// 恢复
async function cfgBackupRecoveryCb(filename) {
  await ElMessageBox.confirm("确认恢复已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "danger"
  });
  await cfgBackupRecovery({
    fname: filename
  });
  ElMessage.success("操作成功");
  loadDataCb();
}

// 备份
async function cfgBackupCb() {
  await cfgBackup();
  ElMessage.success("操作成功");
  loadDataCb();
}

// 删除
async function cfgBackupDelCb(filename) {
  await ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "danger"
  });
  const res = await cfgBackupDel({
    fname: filename
  });
  console.log(res);
  loadDataCb();
  ElMessage.success("操作成功");
}

const urlDownload = function (url, name) {
  var a = document.createElement("a");
  // console.log(url)
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  const clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

async function templateOperate(type, file = "") {
  if (type === "export") {
    const res = await exportData();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await cfgBackupDownload({
      fname: file
    });
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `backup_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await cfgBackupUpload({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <div>
        <BaseCollapse title="">
          <template #header>
            <div class="h-box justify-end" style="width: 300px; float: right" @click.stop>
              <base-button @click="templateOperate('import')" type="import_icon_text"></base-button>
              <base-button @click="cfgBackupCb" type="sbackup_icon"></base-button>
            </div>
          </template>
          <div class="h-box">
            <el-form-item label="">
              <el-checkbox label="自动备份" v-model="formData.isInterval" />
            </el-form-item>

            <el-form-item class="mg-l-sm">
              <el-input v-if="formData.isInterval" v-model="formData.interval" style="width: 70px" placeholder="请输入" />
              <span v-if="formData.isInterval">天</span>
            </el-form-item>
            <el-form-item class="mg-l-lg" label="备份内容">
              <el-checkbox-group v-model="formData.data">
                <el-checkbox :value="1" label="策略" />
                <el-checkbox :value="2" label="告警封堵日志" />
                <el-checkbox :value="4" label="原始日志" />
              </el-checkbox-group>
            </el-form-item>

            <div class="mg-l-sm" style="margin-bottom: 18px">
              <base-button @click="ftpCfgSetCb" type="save_icon_text"></base-button>
              <base-button @click="ftpCfgGetCb" type="refresh_icon_text_small"></base-button>
            </div>
          </div>
        </BaseCollapse>
      </div>
    </template>
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total||0"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="false"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      :loading="loading"
    >
      <template #fileDefault="{ data }">
        {{ data.row.file.replaceAll("l7fwd_", "")}}
      </template>
      <template #operationDefault="{ data }">
        <base-button @click="cfgBackupRecoveryCb(data.row.file)" type="backup_icon"></base-button>
        <base-button @click="templateOperate('download', data.row.file)" type="download_icon"></base-button>
        <base-button @click="cfgBackupDelCb(data.row.file)" type="del_icon_text"></base-button>
      </template>
    </he-table>
  </BaseUpDown>
</template>
